package com.climber.android.component.webview.mvp.ui.base

import android.annotation.SuppressLint
import android.content.Intent
import android.text.TextUtils
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.util.UIHelper
import com.climber.android.commonres.widget.loading.GLoadingDefaultAdapter
import com.climber.android.commonres.widget.loading.GlobalLoadingStatusView
import com.climber.android.component.webview.R
import com.climber.android.component.webview.di.component.DaggerBaseWebComponent
import com.climber.android.component.webview.mvp.contract.BaseWebContract
import com.climber.android.component.webview.mvp.presenter.BaseWebPresenter
import io.ganguo.library.dswebview.DSWebView
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.library.android.loading.Gloading

/**
 * Created by Mikes at 2019/4/28 2:44 PM
 */
abstract class BaseWebActivity : BaseMVPActivity<BaseWebPresenter>(), BaseWebContract.View {
    protected lateinit var mLoadingAndRetryManager: Gloading.Holder
    protected lateinit var webContainerOfActivity: FrameLayout

    private lateinit var baseBridgeWebView: DSWebView

//    var tvCloseWebBtn: TextView? = null

    protected var shouldBreakBack = false

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerBaseWebComponent.builder()
            .appComponent(appComponent)
            .view(this)
            .build()
            .inject(this)
    }

    override fun getLayoutResourceId(): Int {
        return R.layout.web_activity_base_web
    }

    override fun initView() {
//        tvCloseWebBtn = findViewById<TextView>(R.id.tvCloseWebBtn)
//        updateWebCloseBtnVisibility(false)
//        tvCloseWebBtn?.setOnClickListener { v -> this.finish() }

        window.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)

        webContainerOfActivity = findViewById(R.id.webContainerOfActivity)

        val title = intent.getStringExtra(AppConstants.PARAM_WEB_TITLE) ?: ""
        setWebTitle(title)

        configWebView()
    }

    // 1级页面不显示关闭按钮，页面内发生重定向后，在2级以后的页面显示关闭按钮
    override fun updateWebCloseBtnVisibility(isShowCloseBtn: Boolean) {
//        tvCloseWebBtn?.visibility =  if (isShowCloseBtn) {
//            View.VISIBLE
//        } else {
//            View.GONE
//        }
    }

    override fun setWebTitle(title: String) {
        if (!TextUtils.isEmpty(title)) {
            setToolBarTitle(title)
        } else {
            setToolBarTitle("")
        }
    }

    override fun initListener() {
        mLoadingAndRetryManager =
            Gloading.from(GLoadingDefaultAdapter()).wrap(webContainerOfActivity)
                .withStatusClick { status ->
                    when (status) {
                        GlobalLoadingStatusView.STATUS_RETRY -> reloadWebUI()
                    }
                }
    }

    override fun initData() {
        shouldBreakBack = intent.getBooleanExtra(AppConstants.PARAM_BREAK_BACK, false)

        handleJavaScript()
        initIntentData()
        injectWebInitData()
    }

    @SuppressLint("JavascriptInterface")
    private fun configWebView() {
        baseBridgeWebView = DSWebView(this)
        val params = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        getWebView().layoutParams = params
        webContainerOfActivity.addView(getWebView())

        mPresenter.initBridgeWebviewConfig(getWebView())
    }

    protected fun reloadWebUI() {
        mLoadingAndRetryManager.showContent()
        webContainerOfActivity.removeAllViews()

        configWebView()

        handleJavaScript()
        injectWebInitData()
    }

    override fun onBackPressed() {
        if (shouldBreakBack && getWebView().canGoBack()) {
            getWebView().goBack()

            if (!getWebView().canGoBack()) {
                updateWebCloseBtnVisibility(false)
            }
        } else {
            super.onBackPressed()
        }
    }

    override fun onResume() {
        super.onResume()
        getWebView().onResume()
    }

    override fun onPause() {
        super.onPause()
        getWebView().onPause()
    }

    override fun onDestroy() {
        val webViewParent = getWebView().parent
        if (webViewParent is ViewGroup) {
            webViewParent.removeView(getWebView())
        }

        getWebView().clearHistory()
        getWebView().destroy()

        super.onDestroy()
    }

    override fun getActivity(): BaseWebActivity {
        return this
    }

    override fun killMyself() {
        finish()
    }

    override fun showWebLoading() {
        UIHelper.showLoading(this, null)
    }

    override fun hideWebLoading() {
        UIHelper.hideLoading()
    }

    override fun showWebViewError(preferHtmlUrl: String) {
        hideWebLoading()
        mLoadingAndRetryManager.showLoadingStatus(GlobalLoadingStatusView.STATUS_RETRY)
    }

    override fun getWebView(): DSWebView {
        return baseBridgeWebView
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mPresenter.onActivityResult(requestCode, resultCode, data)
    }
}
